package cn.com.miao.lynx.common.base.controller;

import cn.com.miao.lynx.common.base.mapping.BaseMapStructMapping;
import cn.com.miao.lynx.common.base.model.BaseModel;
import cn.com.miao.lynx.common.base.service.BaseService;
import cn.com.miao.lynx.common.core.model.PageParam;
import cn.com.miao.lynx.common.core.model.Result;
import cn.com.miao.lynx.common.dict.annotation.DictAssembly;
import cn.com.miao.lynx.common.log.annotation.Log;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;

/**
 * BaseController
 *
 * @title: BaseController
 * @description:
 * @author: dengmiao
 * @create: 2019-12-23 17:29
 **/
public interface BaseController<E extends BaseModel<ID>, ID extends Serializable> extends CommonController {

    /**
     * 获取注入的service
     * @return BaseService
     */
    BaseService<E, ID> getService();

    /**
     * 获取注入的mapStruct转化bean
     * 非必须 可null
     * @return BaseMapStructMapping
     */
    default BaseMapStructMapping<E, ID> getMapStructMapping() {
        return getService().getMapStructMapping();
    }

    /**
     * 获取泛型的类模板对象
     * @param index 泛型的下标
     * @return Class
     */
    private Class<?> getClazz(int index) {
        return getService().getClazz(index);
    }

    @PostMapping("add")
    default ResponseEntity<Result> add(@RequestBody @Valid E entity) {
        return wrap(Result.ok(getService().create(entity)));
    }

    @DeleteMapping("delete/{id}")
    default ResponseEntity<Result> delete(@PathVariable ID id) {
        getService().delete(id);
        return wrap(Result.ok());
    }

    @PutMapping("update")
    default ResponseEntity<Result> update(@RequestBody @Valid E entity) {
        return wrap(Result.ok(getService().update(entity)));
    }

    @Log("列表")
    @DictAssembly
    @GetMapping("list")
    default ResponseEntity<Result> list() {
        return wrap(Result.ok(getService().list()));
    }

    @GetMapping("page")
    default ResponseEntity<Result> page(@ModelAttribute PageParam pageParam) {
        Pageable pageable = toPageAble(pageParam);
        return wrap(Result.ok(getService().page(pageable)));
    }
}
